package org.dearsor.elective.controller;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;

import org.dearsor.elective.exception.CreditOverflowExeption;
import org.dearsor.elective.model.Person;
import org.dearsor.elective.model.Student;
import org.dearsor.elective.service.CourseMgr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
//@SessionAttributes("courseList")
public class CourseController {
	
	@Autowired private CourseMgr courseMgr;
	
	@PersistenceContext
	private EntityManager em;
	
	@RequestMapping(method = RequestMethod.GET,value="/select")
	public String select(@RequestParam(value = "courseId") long courseId,HttpServletRequest request) {
		// TODO Auto-generated method stub
		Person person = (Person) request.getSession().getAttribute("currentUser");
		if (person == null) {
			return "needLogin";
		}
		try {
			courseMgr.doSelect(courseId,person);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		} catch (CreditOverflowExeption e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "creditOverflow";
		}
//		return "prompt";
		return "redirect:/courseList";
	}
	
	@RequestMapping(method = RequestMethod.GET,value="/unselect")
	public String unselect(@RequestParam(value = "courseId") long courseId,HttpServletRequest request) {
		// TODO Auto-generated method stub
		Person person = (Person) request.getSession().getAttribute("currentUser");
		if (person == null) {
			return "needLogin";
		}
		try {
			courseMgr.doUnselect(courseId,person);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}
//		return "prompt";
		return "redirect:/courseList";
	}
	
//	@ModelAttribute("courseList")
	@RequestMapping(value = "/courseList")
	public String courseList(ModelMap modelMap, HttpServletRequest request) {
		Person person = (Person) request.getSession().getAttribute("currentUser");
		if (person == null) {
			return "needLogin";
		}
		Student student = em.find(Student.class, person.getId());
		modelMap.put("availableCourseList", courseMgr.listAvailableCourses(student));
		modelMap.put("selectedCourseList", student.getCourses());
		return "courseList";
	}

}
